package cn.easy.rpc.beans;

import cn.easy.rpc.annotations.RpcInstance;
import cn.easy.rpc.config.ConfigHolder;
import cn.easy.rpc.core.ServiceSchema;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


/**
 * 服务发现
 *
 * @author zwb
 * @create 2020-09-04 22:52
 **/
@Component
public class RpcDiscoveryPostProcessor implements BeanPostProcessor, ApplicationListener<ContextRefreshedEvent> {

    private static final Log logger = LogFactory.getLog(RpcDiscoveryPostProcessor.class);

    private final List<ServiceSchema> registeredBean = new ArrayList<>();
    private final Set<String> schemaSet = new HashSet<>();

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        RpcInstance rpcInstance = null;
        if ((rpcInstance = bean.getClass().getDeclaredAnnotation(RpcInstance.class)) != null) {
            if (schemaSet.contains(rpcInstance.schema()))
                throw new RuntimeException("service schema can not be repeat,schame:" + rpcInstance.schema());
            logger.info("Found rpc bean name : " + beanName);
            ServiceSchema serviceSchema = new ServiceSchema();
            serviceSchema.setBeanName(beanName);
            serviceSchema.setSchema(rpcInstance.schema());
            registeredBean.add(serviceSchema);
            schemaSet.add(rpcInstance.schema());
        }
        return bean;
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        ConfigHolder.config.setServices(registeredBean);
    }
}
